package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.appointment;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.log.SysLogBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.*;
import com.xiaoxu.intranetweb.util.SzResult;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AppointmentBu {
    @Autowired
    private ITAppointmentService itAppointmentService;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private ITApproveService approveService;
    @Autowired
    private ITApproveInfoService approveInfoService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ICCompanysService cCompanysService;
    @Autowired
    private ICProductsInfoService cProductsService;
    @Autowired
    private SysLogBu sysLogBu;

    //    查询预约信息
    public SzResult getAppointment(String company, String product, String status, String startTime, String endTime, String token, String plantId) throws Exception {
        // String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        QueryWrapper<TAppointment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(company != null && !company.isEmpty(), "A_COMP", company);
        queryWrapper.eq(product != null && !product.isEmpty(), "A_PDT", product);
        queryWrapper.eq(status != null && !status.isEmpty(), "A_STATUS", status);
        queryWrapper.between(startTime != null && !startTime.isEmpty(), "CREATETIME", startTime, endTime);
        queryWrapper.eq("DEL_FLAG", 0);
        queryWrapper.eq("DATA_FROM", plantId);
        List<TAppointment> list = itAppointmentService.list(queryWrapper);
        for (TAppointment tAppointment : list) {
            String creater = tAppointment.getCreater();
            String aComp = tAppointment.getAComp();
            String aPdt = tAppointment.getAPdt();
            QueryWrapper<SysUser> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("ID", creater);
            SysUser sysUser = sysUserService.getOne(queryWrapper1);
            if (sysUser == null) {
                tAppointment.setCreater(null);
            } else {
                tAppointment.setCreater(sysUser.getTrueName());
            }
            QueryWrapper<CCompanys> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("ID", aComp);
            CCompanys cCompanys = cCompanysService.getOne(queryWrapper2);
            if (cCompanys == null) {
                tAppointment.setAComp(null);
            } else {
                tAppointment.setAComp(cCompanys.getCpyCo() + "." + cCompanys.getCpyChico());
            }
            QueryWrapper<CProductsInfo> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.eq("ID", aPdt);
            CProductsInfo cProducts = cProductsService.getOne(queryWrapper3);
            if (cProducts == null) {
                tAppointment.setAPdt(null);
            } else {
                tAppointment.setAPdt(cProducts.getPdtinfPdt());
            }
        }
        return SzResult.success(list);
    }


    //    删除预约信息
    public SzResult deleteAppointment(String id) {
        itAppointmentService.getById(id).setDelFlag(1);
        return SzResult.success("删除成功");
    }


    //    新增预约信息
    public SzResult addAppointment(String cpyId, String productId, String appointCount, String type, String token, String plantId) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        QueryWrapper<CCompanys> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", cpyId);
        CCompanys cCompanys = cCompanysService.getOne(queryWrapper);
        TAppointment tAppointment = new TAppointment();
        tAppointment.setAComp(cpyId);
        tAppointment.setAPdt(productId);
        tAppointment.setAStatus(new BigDecimal(0));
        tAppointment.setACount(new BigDecimal(appointCount));
        tAppointment.setCreater(user.getTrueName());
        tAppointment.setCreatetime(LocalDateTime.now());
        tAppointment.setAType(type);
        tAppointment.setDelFlag(0);
        tAppointment.setDataFrom(plantId);
        itAppointmentService.save(tAppointment);
        String unit = "";
        if (type.equals("0")) {
            unit = "车";
        }
        if (type.equals("1")) {
            unit = "吨";
        }
        QueryWrapper<CProductsInfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ID", productId);
        CProductsInfo cProductsInfo = cProductsService.getOne(queryWrapper1);
        return SzResult.success("新增成功,请等待审批,确定成功预约量");
    }

    /**
     * 审批预约信息
     */
    public SzResult approveAppointment(String id, String status, String winCount, String token, String plantId) throws Exception {


        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        QueryWrapper<TAppointment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        TAppointment tAppointment = itAppointmentService.getOne(queryWrapper);
        if (tAppointment == null) {
            return SzResult.error("预约信息不存在");
        }
        if (tAppointment.getAStatus().intValue() != 0) {
            return SzResult.error("预约信息已审批");
        }
        String unit = "";
        if (tAppointment.getAType().equals("0")) {
            unit = "车";
        }
        if (tAppointment.getAType().equals("1")) {
            unit = "吨";
        }

        QueryWrapper<CProductsInfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ID", tAppointment.getAPdt());
        CProductsInfo cProductsInfo = cProductsService.getOne(queryWrapper1);
        QueryWrapper<CCompanys> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("ID", tAppointment.getAComp());
        CCompanys cCompanys = cCompanysService.getOne(queryWrapper2);
        StringBuilder logMsg = new StringBuilder();
        logMsg.append("预约公司:").append(cCompanys.getCpyCo()).append(".").append(cCompanys.getCpyChico()).append("预约产品:").append(cProductsInfo.getPdtinfPdt()).append("预约量:").append(tAppointment.getACount()).append(unit);
        if (status.equals("1")) {
            if (winCount == null || winCount.isEmpty()) {
                return SzResult.error("成功预约量不能为空");
            }
            if (Integer.parseInt(winCount) > Integer.parseInt(tAppointment.getACount().toString())) {
                return SzResult.error("成功预约量不能大于预约量");
            }
            tAppointment.setAStatus(new BigDecimal(1));
            tAppointment.setWinCount(new BigDecimal(winCount));
            tAppointment.setAApproveBy(user.getTrueName());
            tAppointment.setAApproveTime(LocalDateTime.now());
            itAppointmentService.updateById(tAppointment);
            sysLogBu.logRecord("预约审批", user.getTrueName(), "审批通过：【" + logMsg + "】" + "成功预约量为：【" + winCount + "】" + unit, tAppointment.getDataFrom());
            return SzResult.success("审批成功");
        }
        if (status.equals("2")) {
            tAppointment.setAStatus(new BigDecimal(2));
            tAppointment.setAApproveBy(user.getTrueName());
            tAppointment.setAApproveTime(LocalDateTime.now());
            tAppointment.setWinCount(new BigDecimal(0));
            itAppointmentService.updateById(tAppointment);
            sysLogBu.logRecord("预约审批", user.getTrueName(), "审批不通过：【" + logMsg + "】", tAppointment.getDataFrom());
            return SzResult.success("审批成功");
        }
        return SzResult.error("审批失败");
    }


    /**
     * 修改预约信息
     */
    public SzResult updateAppointment(String id, String appointCount, String token, String plantId) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        QueryWrapper<TAppointment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        TAppointment tAppointment = itAppointmentService.getOne(queryWrapper);
        if (tAppointment == null) {
            return SzResult.error("预约信息不存在");
        }
        if (tAppointment.getAStatus().intValue() != 0) {
            return SzResult.error("预约信息已审批");
        }
        String unit = "";
        if (tAppointment.getAType().equals("0")) {
            unit = "车";
        }
        if (tAppointment.getAType().equals("1")) {
            unit = "吨";
        }
        QueryWrapper<CProductsInfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ID", tAppointment.getAPdt());
        queryWrapper1.eq("PDTINF_DELETED", 0);
        queryWrapper1.eq("DATA_FROM", plantId);
        CProductsInfo cProductsInfo = cProductsService.getOne(queryWrapper1);
        QueryWrapper<CCompanys> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("ID", tAppointment.getAComp());
        queryWrapper2.eq("CPY_DELETED", 0);
        queryWrapper2.eq("DATA_FROM", plantId);
        CCompanys cCompanys = cCompanysService.getOne(queryWrapper2);
        String logMsg = "预约公司:" + cCompanys.getCpyCo() + "." + cCompanys.getCpyChico() + "预约产品:" + cProductsInfo.getPdtinfPdt() + "预约量:" + tAppointment.getACount() + unit;
        tAppointment.setACount(new BigDecimal(appointCount));
        itAppointmentService.updateById(tAppointment);
        sysLogBu.logRecord("预约审批", user.getTrueName(), "修改预约信息：【" + logMsg + "】" + "修改后预约量为：【" + appointCount + "】" + unit, tAppointment.getDataFrom());
        return SzResult.success("修改成功");
    }
}
